#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>


int play_wav_test(void) 
{
    int err;
    snd_pcm_t *pcm_handle;
    snd_pcm_hw_params_t *params;
    unsigned int pcm_channels = 2; // 声道数
    unsigned int pcm_rate = 44100; // 采样率
    unsigned int pcm_period_size = 1024; // 每个周期的采样数

    //err = snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0);
    err = snd_pcm_open(&pcm_handle, "plughw:0,0", SND_PCM_STREAM_PLAYBACK, 0); 
    if (err < 0) {
        fprintf(stderr, "无法打开PCM设备: %s\n", snd_strerror(err));
        return 1;
    }   

    // 初始化参数结构体
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(pcm_handle, params);
    snd_pcm_hw_params_set_access(pcm_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
    snd_pcm_hw_params_set_format(pcm_handle, params, SND_PCM_FORMAT_S16_LE);
    snd_pcm_hw_params_set_channels(pcm_handle, params, pcm_channels);
    snd_pcm_hw_params_set_rate_near(pcm_handle, params, &pcm_rate, 0); 

    // 设置硬件参数
    err = snd_pcm_hw_params(pcm_handle, params);
    if (err < 0) {
        fprintf(stderr, "无法设置硬件参数: %s\n", snd_strerror(err));
        return 1;
    }   

    // 打开PCM设备
    err = snd_pcm_prepare(pcm_handle);
    if (err < 0) {
        fprintf(stderr, "无法打开PCM设备: %s\n", snd_strerror(err));
        return 1;
    }   

    // 打开PCM音频文件
    FILE *pcm_file = fopen("/home/ubuntu24/music/00.wav", "rb");
    if (!pcm_file) {
        fprintf(stderr, "无法打开PCM音频文件\n");
        return 1;
    }   

    // 读取PCM数据并播放
    char pcm_data[pcm_period_size * 4]; // 4 bytes per sample for 16-bit stereo (2 channels)
    while (fread(pcm_data, sizeof(char), sizeof(pcm_data), pcm_file) > 0) {
        err = snd_pcm_writei(pcm_handle, pcm_data, pcm_period_size);
        if (err < 0) {
            fprintf(stderr, "写入PCM数据失败: %s\n", snd_strerror(err));
            break;
        }   
    }

    // 关闭文件和PCM设备
    fclose(pcm_file);
    snd_pcm_close(pcm_handle);
    
    return 0;
}

